<?php

namespace App\Models\Activity;

use App\App\Services\Web\UserService;
use App\Contracts\Repositories\ActivityRepository as Activities;
use App\Entities\ActivityModel;
use Illuminate\Container\Container;

class ActivityService
{
    const ACTIVITY_TYPE = [
        'vote' => 'poll',
        'quiz' => 'default',
    ];

    /**
     * @var Activities
     */
    private $activities;

    public function __construct(Activities $activities)
    {
        $this->activities = $activities;
    }

    /**
     * get activity by user id
     *
     * @param string $userId
     *
     * @return array
     */
    public function getActivityByUser($userId)
    {
        return $this->activities->findByUserId($userId);
    }

    public function getActivityByGroup($groupCode)
    {
        return $this->activities->findByGroupCode($groupCode);
    }

    public function findByUserAndRunning($userId)
    {
        return $this->activities->findRunningByUserId($userId);
    }

    /**
     * create activity
     *
     * @param $data
     *
     * @return Activity|null
     */
    public function createActivity($data)
    {
        $activity = new Activity($data);

        return $this->activities->create($activity);
    }

    public function countByConditions($condition)
    {
        return $this->activities->countByConditions($condition);
    }

    public function saveActivityById($updates, $id)
    {
        return $this->activities->update($updates, ['id' => $id]);
    }

    public function deleteActivity($ids)
    {
        return $this->activities->deleteByIds($ids);
    }

    public function findOne($id)
    {
        return $this->activities->findOne($id);
    }

    public function getActivityIdsByTpl($tplId)
    {
        return $this->activities->findByTpl($tplId, ['id']);
    }

    public function getFinishedActivities()
    {
        return $this->activities->getFinishedActivities();
    }
    public function getFinishedActivitiesOneMonthsAgo()
    {
        return $this->activities->getFinishedActivitiesOneMonthsAgo();
    }
    public function getDeletedActivitiesOneMonthAgo(){
        return $this->activities->getDeletedActivitiesOneMonthAgo();
    }

    /**
     * 获取某一类型的活动
     * @param $type
     * @param array $columns
     * @param bool $grouped
     * @return mixed
     */
    public function findByActivityModelType($type, $columns = ['*'], $grouped = false)
    {
        $modelIds = ActivityModel::query()
            ->where('type', $type)
            ->pluck('id');

        $query = \App\Entities\Activity::query();

        if ($grouped) {
            $user = Container::getInstance()->make(UserService::class);
            $query->where('group_code', $user->getGroupCode());
        }

        $query->whereIn('model_id', $modelIds);

        return $query->get($columns);
    }
}
